package x.y.z;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LeetCode_0438 {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        int left = 0;
        int right = 0;
        Map<Character, Integer> needs = new HashMap<>();
        Map<Character, Integer> windows = new HashMap<>();
        for (int i = 0; i < p.length(); i++) {
            char ch = p.charAt(i);
            needs.put(ch, needs.getOrDefault(ch, 0) + 1);
        }

        int matchs = 0;
        while (right < s.length()) {
            char ch = s.charAt(right);
            if (needs.containsKey(ch)) {
                windows.put(ch, windows.getOrDefault(ch, 0) + 1);
                if (windows.get(ch).equals(needs.get(ch))) {
                    matchs++;
                }
            }
            right++;

            while (matchs == needs.size()) {
                if (right - left == p.length()) {
                    result.add(left);
                }
                char c = s.charAt(left);
                if (needs.containsKey(c)) {
                    windows.put(c, windows.getOrDefault(c, 0) - 1);
                    if (windows.get(c) < needs.get(c)) {
                        matchs--;
                    }
                }
                left++;
            }
        }
        return result;
    }
}
